/**
 * Copyright (c) 2011-9-23 WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.wkm.task.factory;

import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wkm.xstream.XStreamUtil;

/**
 * The class note
 * @version 1.0 2012-1-17
 * @author WUKUNMENG
 */
public class SchedulerFactoryUtil {
	
	private SchedulerFactory sf = new StdSchedulerFactory();

	private Scheduler scheduler = null;
	
	private Logger logger = LoggerFactory.getLogger(SchedulerFactoryUtil.class);
	
//	private DataReader reader = DataReader.getInstance();
		
	public SchedulerFactoryUtil(){
		try{
			scheduler = sf.getScheduler();
		} catch (SchedulerException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 添加任务
	 * @param c
	 * @param cron
	 */
	public void addJob(Class<? extends Job> c,String cron){
		try{
			int groupNum = -1;
			List<String> groupNames = scheduler.getJobGroupNames();
			if(groupNames == null){
				groupNum = 0;
			} else {
				groupNum = groupNames.size();
			}
			
			scheduler.scheduleJob(
					createJobDetail(c,"group" + groupNum), 
					createTrigger(cron,"group" + groupNum));
		} catch (SchedulerException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		
	}
	
	/**
	 * 启动
	 */
	public void bootup(){
		try{
			if(!scheduler.isStarted()){
				scheduler.start();
			}
		} catch (SchedulerException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 关闭
	 */
	public void stop(){
		try{
			if(scheduler.isStarted()){
				scheduler.shutdown();
			}
		} catch (SchedulerException e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	
	private JobDetail createJobDetail(Class<? extends Job> c,String groupName){
		return JobBuilder.newJob(c).withIdentity("job",groupName).build();
	}
	
	private Trigger createTrigger(String cron,String groupName){
		return TriggerBuilder.newTrigger()		
				.withIdentity("trigger", groupName)
				.withSchedule(CronScheduleBuilder.cronSchedule(cron))
				.build();
	}
	
	public void addSchedulerBean(SchedulerBean sb){
		//写入
		XStreamUtil.write(sb, sb.getId());
		//读取
		XStreamUtil.read(new SchedulerBean(), sb.getId());
	}
}
